package com.xhwl.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.Attr;
import com.xhwl.common.pojo.cent.sdata.AttrScene;
import com.xhwl.common.pojo.cent.sdata.AttrSceneRelation;
import com.xhwl.common.pojo.cent.sdata.Enterprise;
import com.xhwl.common.query.cent.sdata.AttrQuery;
import com.xhwl.common.query.cent.sdata.AttrSceneQuery;
import com.xhwl.common.utils.StringUtils;
import com.xhwl.data.dao.IAttrDao;
import com.xhwl.data.dao.IAttrSceneRelationDao;
import com.xhwl.data.dao.IEnterpriseDao;
import com.xhwl.data.service.IAttrSceneService;
import com.xhwl.data.service.IAttrService;
import com.xhwl.data.service.IEnterpriseService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: zhangliuli
 * @Description:
 * @Date: Create in 2023/4/11
 */
@Service
public class AttrServiceImpl extends ServiceImpl<IAttrDao, Attr> implements IAttrService {
    @Autowired
    private IEnterpriseDao enterpriseDao;
    @Autowired
    private IAttrDao attrDao;
    @Autowired
    private IAttrService attrService;
    @Autowired
    private IEnterpriseService enterpriseService;
    @Autowired
    private IAttrSceneService attrSceneService;
    @Autowired
    private IAttrSceneRelationDao attrSceneRelationDao;

    @Override
    public boolean save(Attr attr) {
        return false;
    }

    /**
     * 属性配置新增
     */
    @Override
    public ResultJson create(Attr attr) {
        // 1判断必填参数是否有传参
        if (attr.getName().trim()== null || attr.getName().trim().length() > 6||attr.getName().trim().length() ==0) {
            return ResultJson.fail("企业属性名称参数错误！");
        }
        if (attr.getCode().trim() == null || attr.getCode().trim().length() > 18||attr.getCode().trim().length() ==0) {
            return ResultJson.fail("企业属性编码参数错误！");
        }
        //新增属性分类，通用属性不需要选择运营商
        //2023-9-2 中建项目未上线属性分类
        if (null == attr.getAttrClassify()){
            attr.setAttrClassify(2);
//            return ResultJson.fail("参数错误，属性分类为空");
        }
        if (attr.getAttrClassify().equals(2)){
            if (attr.getEnterpriseId() == null) {
                return ResultJson.fail("运营商企业ID参数错误！");
            }
            Enterprise enterprise = new Enterprise();
            enterprise = enterpriseDao.selectById(attr.getEnterpriseId());
            if (null == enterprise) {
                return ResultJson.fail("该运营商企业不存在");
            }
        }
        if (attr.getType() == null || attr.getType() < 1 || attr.getType() > 3) {
            return ResultJson.fail("企业属性类型参数错误！");
        }
        if (attr.getCreationMethod() == null || attr.getCreationMethod() < 1 || attr.getCreationMethod() > 2) {
            return ResultJson.fail("企业创建方式参数错误！");
        }
        //如果传参，是否已经存在
        if (query(attr) != 0) {
            return ResultJson.fail("企业属性已存在！");
        }
        if (queryCode(attr) != 0) {
            return ResultJson.fail("企业编码已存在！");
        }
        if (attr.getCreationMethod()==2&&attr.getAttrJson()==null) {
            return ResultJson.fail("请输入自定义内容！");
        }
        if(attr.getCreationMethod()==1&&attr.getAttrJson()!=null) {
            return ResultJson.fail("选项为内置，不应该有自定义内容！");
        }
        attrDao.insert(attr);
        return ResultJson.success();
    }
    /**
     * 属性配置修改
     */
    @Override
    public ResultJson update(Attr attr) {
        // 1判断必填参数是否有传参
        if (attr.getId() == null) {
            return ResultJson.fail("属性ID参数错误！");
        }
        int num = attr.getId();
        Attr attrtest1 = attrDao.selectById(num);
        if (attrtest1 == null) {
            return ResultJson.fail("参数错误，id不存在！");
        }
        if (attr.getName().trim() == null || attr.getName().trim().length() > 6 || attr.getName().trim().length() == 0) {
            return ResultJson.fail("企业属性名称参数错误！");
        }
        if (attr.getCode().trim() == null || attr.getCode().trim().length() > 18 || attr.getCode().trim().length() == 0) {
            return ResultJson.fail("企业属性编码参数错误！");
        }
        if (attr.getEnterpriseId() == null) {
            return ResultJson.fail("运营商企业ID参数错误！");
        } else {
            Enterprise enterprise = new Enterprise();
            enterprise = enterpriseDao.selectById(attr.getEnterpriseId());
            if (null == enterprise) {
                return ResultJson.fail("该运营商企业不存在");
            }
        }
        if (attr.getType() == null || attr.getType() < 1 || attr.getType() > 3) {
            return ResultJson.fail("企业属性类型参数错误！");
        }
        if (attr.getCreationMethod() == null || attr.getCreationMethod() < 1 || attr.getCreationMethod() > 2) {
            return ResultJson.fail("企业创建方式参数错误！");
        }
        if (attr.getCreationMethod() == 2 && attr.getAttrJson() == null) {
            return ResultJson.fail("请输入自定义内容！");
        }
        if (attr.getCreationMethod() == 1 && attr.getAttrJson() != null) {
            return ResultJson.fail("选项为内置，不应该有自定义内容！");
        }
        //默认设置为通用属性
        if (null == attr.getAttrClassify()){
            attr.setAttrClassify(1);
        }
        Attr attrtest = attrDao.selectById(attr.getId());
        //如果名字和编码都不存在，就根据id修改；
        //名字不存在，编码为id对应编码，也可以修改
        if (query(attr) == 0 && (queryCode(attr) == 0||attr.getCode().equals(attrtest.getCode()))) {
            attrDao.updateById(attr);
            return ResultJson.success();
        }
        //如果名字存在
        if (attr.getName().equals(attrtest.getName())) {
            if (attr.getCode().equals(attrtest.getCode()) || queryCode(attr) == 0) {
                attrDao.updateById(attr);
                return ResultJson.success();
            } else {
                return ResultJson.fail("参数错误，名字与编码不对应或编码已存在！");
            }
        }else {
            return ResultJson.fail("参数错误，配置信息错误！");
        }
    }
    /**
     * 配置属性删除
     */
    @Override
    public ResultJson delete(Integer id) {
        Attr attr=attrDao.selectById(id);
        if (attr==null) {
            return ResultJson.fail("参数错误，数据不存在");
        } else {
            attrDao.deleteById(id);
            return ResultJson.success();
        }
    }
    /**
     * 属性list
     */

    @Override
    public List<Attr> list(AttrQuery attrQuery){
        //查询特定场景编码的attr
        if (StringUtils.isNotEmpty(attrQuery.getAttrSceneCode()) && null != attrQuery.getEnterpriseId()){
            AttrSceneQuery attrSceneQuery = new AttrSceneQuery();
            attrSceneQuery.setEnterpriseId(attrQuery.getEnterpriseId());
            attrSceneQuery.setCode(attrQuery.getAttrSceneCode());
            List<AttrScene> attrScenes = attrSceneService.list(attrSceneQuery);
            List<Integer> ids = new ArrayList<>();
            if (!attrScenes.isEmpty()){
                QueryWrapper<AttrSceneRelation> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("attr_scene_id",attrScenes.get(0).getId());
                ids = attrSceneRelationDao.selectList(queryWrapper).stream().map(AttrSceneRelation::getAttrId).collect(Collectors.toList());
            }
            attrQuery.setIdList(ids);
        }
        //查询企业可选的所有attr(通用+企业特有)
        if (StringUtils.isEmpty(attrQuery.getAttrSceneCode()) && null != attrQuery.getEnterpriseId()){
            QueryWrapper<Attr> attrQueryWrapper = new QueryWrapper<Attr>().eq("attr_classify", 1).or().eq("enterprise_id", attrQuery.getEnterpriseId());
            List<Integer> commonAttrIdList = attrDao.selectList(attrQueryWrapper).stream().map(Attr::getId).collect(Collectors.toList());
            attrQuery.setIdList(commonAttrIdList);
        }
        if(CollectionUtils.isEmpty(attrQuery.getIdList())){
            return null;
        }
        List<Attr> attrList = attrDao.selectList(new QueryWrapper<Attr>().in("id", attrQuery.getIdList().stream().distinct().collect(Collectors.toList())));
        if (CollectionUtils.isEmpty(attrList)) {
            return attrList;
        }
        List<Integer> enterpriseIds = attrList.stream().map(Attr::getEnterpriseId).collect(Collectors.toList());
        List<Enterprise> enterpriseList = enterpriseDao.selectList(new QueryWrapper<Enterprise>().in("id", enterpriseIds));
        Map<Integer, List<Enterprise>> enterpriseMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(enterpriseList)) {
            enterpriseMap = enterpriseList.stream().collect(Collectors.groupingBy(Enterprise::getId));
        }
        for (Attr attr : attrList) {
            if (!CollectionUtils.isEmpty(enterpriseMap.get(attr.getEnterpriseId()))) {
                attr.setEnterpriseName(enterpriseMap.get(attr.getEnterpriseId()).get(0).getName());
            }
        }
        return attrList;
    }
    /**
     * 查询数据库表中的attr
     */
    @Override
    public int query(Attr attr) {
        QueryWrapper<Attr> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("name").eq("name",attr.getName())
                .eq("enterprise_id",attr.getEnterpriseId());
        int sum = count(queryWrapper);
        return sum;
    }
    /**
     * 查询数据库表中的code
     */
    @Override
    public int queryCode(Attr attr) {
        QueryWrapper<Attr> queryWrapper = new QueryWrapper<>();
        //企业属性编码唯一
        queryWrapper.eq("code", attr.getCode());
        int sum = count(queryWrapper);
        return sum;
    }

    @Override
    public List<Attr> findEntAttr(AttrQuery attrQuery) {
        if (null == attrQuery.getEnterpriseId() || null == attrQuery.getAttrSceneCode()){
            return Collections.EMPTY_LIST;
        }
        QueryWrapper<AttrScene> attrSceneQueryWrapper = new QueryWrapper<AttrScene>().eq("enterprise_id", attrQuery.getEnterpriseId()).eq("code", attrQuery.getAttrSceneCode());
        AttrScene attrScene = attrSceneService.getOne(attrSceneQueryWrapper);
        if (null == attrScene) {
            return Collections.EMPTY_LIST;
        }
        QueryWrapper<AttrSceneRelation> enterpriseAttrRelationQW = new QueryWrapper<AttrSceneRelation>().eq("attr_scene_id", attrScene.getId());
        List<Integer> attrIds = attrSceneRelationDao.selectList(enterpriseAttrRelationQW).stream().map(AttrSceneRelation::getAttrId).collect(Collectors.toList());
        List<Attr> attrList = attrService.list(new QueryWrapper<Attr>().in("id", attrIds));
        return attrList;
    }

    /**
     * 属性page
     */
    @Override
    public Page<Attr> page(Page page, AttrQuery attrQuery) {
        Page<Attr> page1 = attrDao.page(page, attrQuery);
        List<Attr> records = page1.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return page1;
        }
        List<Integer> enterpriseIds = records.stream().map(Attr::getEnterpriseId).collect(Collectors.toList());
        List<Enterprise> enterpriseList = enterpriseDao.selectList(new QueryWrapper<Enterprise>().in("id", enterpriseIds));
        Map<Integer, List<Enterprise>> enterpriseMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(enterpriseList)) {
            enterpriseMap = enterpriseList.stream().collect(Collectors.groupingBy(Enterprise::getId));
        }
        for (Attr attr : records) {
            if (!CollectionUtils.isEmpty(enterpriseMap.get(attr.getEnterpriseId()))) {
                attr.setEnterpriseName(enterpriseMap.get(attr.getEnterpriseId()).get(0).getName());
            }
        }
        return page1;
    }
}
